package personal.vivian.logic;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@Slf4j
public class ExecTask {
    public static final ExecutorService executors = Executors.newFixedThreadPool(100);
    public static final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(8, 8, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(8));
    Logger logger = LoggerFactory.getLogger(ExecTask.class);

    public List<Executor.Task> generateTask(boolean async, int batchSize, List<String> datas) {
        List<Executor.Task> tasks = new ArrayList<>();
        Executor.Task task = null;
        CountDownLatch countDownLatch = new CountDownLatch(2);
        AtomicInteger atomicInteger = new AtomicInteger(2);
      /*  CyclicBarrier barrier=new CyclicBarrier(2, new Runnable() {
            @Override
            public void run() {
                System.out.println("aasync bbb thread name"+Thread.currentThread().getName());
                System.out.println("aasync bbb run");

            }
        });*/
        if (async) {
            //task = new Executor.AsyncTask(barrier);
            task = new Executor.AsyncTask(atomicInteger);
            Executor.Task task2 = new Executor.AsyncTask(atomicInteger);

            // Executor.Task task2 =new Executor.AsyncTask(barrier);
            tasks.add(task);
            tasks.add(task2);
            for (Executor.Task taski : tasks) {
                threadPool.submit(taski);
                System.out.println("ssssss bbb thread name" + Thread.currentThread().getName());

                System.out.println("sssss bbb run");

            }
        } else {
            task = new Executor.syncTask(countDownLatch);
            Executor.Task task2 = new Executor.syncTask(countDownLatch);
            tasks.add(task);
            tasks.add(task2);
            for (Executor.Task taski : tasks) {
                executors.submit(taski);
            }
            try {
                countDownLatch.await();
                logger.info("log sync finish");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }


        return tasks;
    }

    public void execTask(List<String> datas) {
        List<Executor.Task> tasks = generateTask(false, 1, datas);
        for (Executor.Task task : tasks) {
            executors.submit(task);
        }


    }

}
